import os


# 读取文件
def read_text_file(file_path):
    list = []
    try:
        with open(file_path, "r", encoding="utf-8") as file:
            for line in file:
                list.append(line.strip())
            return list
    except FileNotFoundError:
        print(f"文件不存在: {file_path}")
    except Exception as e:
        print(f"读取文件时出错: {e}")


# 写入文件
def write_text_file(file_path, list):
    try:
        with open(file_path, "w", encoding="utf-8") as f:
            for item in list:
                f.write(f"{item}\n")  # 写入元素并添加换行符
    except FileNotFoundError:
        print(f"文件不存在: {file_path}")
    except Exception as e:
        print(f"读取文件时出错: {e}")


#  格式化行文本
def format_line_text(line):
    return line


script_dir = os.path.dirname(os.path.abspath(__file__))
# 组装原始目录文件路径
dir_text_file_path = os.path.join(script_dir, "原始目录.txt")
# 组装原始目录文件内容
dir_text_file_data_list = read_text_file(dir_text_file_path)

result = []
for item in dir_text_file_data_list:
    if not item:
        continue
    index1 = item.find("…")
    # 处理掉 …………………………………245 这种字符串
    if index1 != -1:
        item = item[:index1]
    # 处理掉 本章练习
    index2 = item.find("本章练习")
    if index2 != -1:
        continue
    # 制表位缩进
    count = item.count(".")
    for i in range(count):
        item = "\t" + item
    result.append(item)

# 结果写入文件
result_file_path = os.path.join(script_dir, "整理好的目录.txt")
write_text_file(result_file_path, result)
